package com.woniu.mealsService.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.annotation.RequireRole;
import com.woniu.dto.OrderDto;
import com.woniu.exception.meals.OrderException;
import com.woniu.exception.meals.StoreException;
import com.woniu.form.AddOrderForm;
import com.woniu.form.CommonsOrderForm;
import com.woniu.form.GetPageOrderForm;
import com.woniu.form.UpdateOrderForm;
import com.woniu.mealsService.config.AliPayConfig;
import com.woniu.mealsService.data.OrderStatus;
import com.woniu.mealsService.model.OrderProduct;
import com.woniu.mealsService.model.Store;
import com.woniu.mealsService.service.OrderProductService;
import com.woniu.mealsService.service.StoreService;
import com.woniu.param.AddOrderParam;
import com.woniu.param.GetPageOrderParam;
import com.woniu.utils.EnumException;
import com.woniu.utils.JwtUtil;
import com.woniu.utils.PageInfo;
import com.woniu.utils.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jodd.util.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author jiang
 * @since 2024年12月10日
 */
@RestController
    @RequestMapping("/orderProduct")
@Api(tags = "订单管理")
@Validated
public class OrderProductController {
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private StoreService storeService;
    @GetMapping("/getOrder")
    @ApiOperation(value = "查询订单详情")
    @RequireRole({"商家","学生"})
    public Result<?> getOrder(@ApiParam("订单编号") @NotNull(message = "订单不能为空") @RequestParam String orderId) throws Exception{
        OrderDto orderDto = orderProductService.getOrder(orderId);
        if(orderDto == null){
            throw new OrderException(EnumException.ORDER_NULL_EXCEPTION);
        }
        return Result.getResult(OrderDto.class).setCode(200).setMsg("查询成功").setData(orderDto);
    }
    @GetMapping("/getUserPageOrder")
    @ApiOperation(value = "查询个人订单")
    @RequireRole({"学生"})
    public Result<?> getUserPageOrder(@Validated @ModelAttribute GetPageOrderForm form , @RequestHeader("token") String token) throws Exception{
        String startTime = null;
        String endTime = null;
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        Integer roleId = claims.get("roleId", Integer.class);
        System.out.println(token);
        System.out.println(userId+" "+roleId);
        GetPageOrderParam bean = BeanUtil.toBean(form, GetPageOrderParam.class);
        if (form.getOrderStatus()==null){
            bean.setOrderStatus(null);
        }else {
            bean.setOrderStatus(Integer.valueOf(form.getOrderStatus()));
        }
        if (form.getOrderStartTime()!=null) {
            LocalDateTime localDateTime = LocalDateTime.parse(form.getOrderStartTime(), DateTimeFormatter.ISO_DATE_TIME);
            // 将时间戳转换为系统默认时区的时间
            LocalDateTime localDateTimeInDefaultZone = localDateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
            // 定义输出格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化时间
            startTime = localDateTimeInDefaultZone.format(outputFormatter);
            bean.setOrderStartTime(startTime);
        }
        if (form.getOrderEndTime()!=null) {
            LocalDateTime localDateTime = LocalDateTime.parse(form.getOrderEndTime(), DateTimeFormatter.ISO_DATE_TIME);
            // 将时间戳转换为系统默认时区的时间
            LocalDateTime localDateTimeInDefaultZone = localDateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
            // 定义输出格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化时间
            endTime = localDateTimeInDefaultZone.format(outputFormatter);
            bean.setOrderEndTime(endTime);
        }
        bean.setUserId(userId);
        bean.setRoleId(roleId);
        bean.setOrderStartTime(startTime);
        PageInfo<OrderDto> pageInfo =orderProductService.getPageOrder(bean);
        return Result.getResult(PageInfo.class).setCode(200).setMsg("查询成功").setData(pageInfo);
    }
    @GetMapping("/getStorePageOrder")
    @ApiOperation(value = "查询商铺所属订单")
    @RequireRole({"商家"})
    public Result<?> getStorePageOrder(@Validated  GetPageOrderForm form,@RequestHeader("token") String token) throws Exception{
        String startTime = null;
        String endTime = null;
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        Integer roleId = claims.get("roleId", Integer.class);
        GetPageOrderParam bean = BeanUtil.toBean(form, GetPageOrderParam.class);
        if (form.getOrderStatus()==null){
            bean.setOrderStatus(null);
        }else {
            bean.setOrderStatus(Integer.valueOf(form.getOrderStatus()));
        }
        if (form.getOrderStartTime()!=null) {
            LocalDateTime localDateTime = LocalDateTime.parse(form.getOrderStartTime(), DateTimeFormatter.ISO_DATE_TIME);
            // 将时间戳转换为系统默认时区的时间
            LocalDateTime localDateTimeInDefaultZone = localDateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
            // 定义输出格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化时间
            startTime = localDateTimeInDefaultZone.format(outputFormatter);
            bean.setOrderStartTime(startTime);
        }
        if (form.getOrderEndTime()!=null) {
            LocalDateTime localDateTime = LocalDateTime.parse(form.getOrderEndTime(), DateTimeFormatter.ISO_DATE_TIME);
            // 将时间戳转换为系统默认时区的时间
            LocalDateTime localDateTimeInDefaultZone = localDateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
            // 定义输出格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化时间
            endTime = localDateTimeInDefaultZone.format(outputFormatter);
            bean.setOrderEndTime(endTime);
        }
        bean.setUserId(userId);
        bean.setRoleId(roleId);
        bean.setOrderStartTime(startTime);
        System.out.println(bean.getUserId()+":"+bean.getRoleId());
        PageInfo<OrderDto> pageInfo =orderProductService.getPageOrder(bean);
        return Result.getResult(PageInfo.class).setCode(200).setMsg("查询成功").setData(pageInfo);
    }

    @PostMapping("/addOrder")
    @ApiOperation(value = "创建订单")
    @RequireRole({"学生"})
    public Result<?> addOrder(@Valid @RequestBody AddOrderForm addOrderForm,@RequestHeader("token") String token) throws Exception{
        Claims claims = JwtUtil.parseToken(token);
        String userId = claims.get("userId").toString();
        String userName = claims.get("userName").toString();
        String userPhone = claims.get("userPhone").toString();
        Store storeServiceOne = storeService.getOne(new LambdaQueryWrapper<Store>().eq(Store::getStoreId, Long.parseLong(addOrderForm.getStoreId())));
        if (storeServiceOne == null){
            throw new StoreException(EnumException.STORE_NULL_EXCEPTION);
        }
        AddOrderParam bean = BeanUtil.toBean(addOrderForm, AddOrderParam.class);
        bean.setUserId(userId);
        bean.setUserName(userName);
        bean.setUserPhone(userPhone);
        bean.setStoreName(storeServiceOne.getStoreName());
        bean.setStorePhone(storeServiceOne.getPhone());
        String val = orderProductService.addOrder(bean);
        return Result.getResult(OrderProduct.class).setCode(200).setMsg(val);
    }
    @PutMapping("/takOrder")
    @ApiOperation(value = "商家接单")
    @RequireRole({"商家"})
    public Result<?> takOrder(@RequestBody @Valid CommonsOrderForm commonsOrderForm, @ApiParam("请求token") @RequestHeader("token") String token) throws Exception{
        Claims claims = JwtUtil.parseToken(token);
        String userId = claims.get("userId").toString();
        String val = orderProductService.takOrder(commonsOrderForm.getOrderId(),userId);
        return Result.getResult(String.class).setCode(200).setMsg(val);
    }
    @PutMapping("/cancelOrder")
    @ApiOperation(value = "取消订单")
    @RequireRole({"商家","学生"})
    public Result<?> cancelOrder(@RequestBody @Valid CommonsOrderForm commonsOrderForm,@ApiParam("请求token") @RequestHeader("token") String token) throws Exception{
        Claims claims = JwtUtil.parseToken(token);
        String userId = claims.get("userId").toString();
        Integer roleId = claims.get("roleId", Integer.class);
        String val = orderProductService.cancelOrder(commonsOrderForm.getOrderId(),userId,String.valueOf(roleId));
        return Result.getResult(String.class).setCode(200).setMsg(val);
    }
    @PostMapping("/pay")
    @ApiOperation(value = "支付订单")
    @RequireRole({"学生"})
    public Result<?> pay(@RequestBody @Valid CommonsOrderForm commonsOrderForm,@RequestHeader("token") String token) throws Exception{
        Claims claims = JwtUtil.parseToken(token);
        String userId = claims.get("userId").toString();
        String url = orderProductService.pay(commonsOrderForm.getOrderId(),userId);
        return Result.getResult(String.class).setCode(200).setMsg("返回支付界面").setData(url);
    }


//    @PutMapping("/updateOrder")
//    @ApiOperation(value = "更新订单状态")
//    public Result<?> updateOrder(@RequestBody UpdateOrderForm updateOrderForm) throws Exception{
//        String msg = orderProductService.updateOrder(updateOrderForm.getOrderId(), updateOrderForm.getOrderState());
//        return Result.getResult(String.class).setCode(200).setMsg(msg);
//    }
    //更新订单为商家备餐中
    @RequireRole({"商家"})
    @PutMapping("/updateOrderReady")
    @ApiOperation(value = "更新订单为商家备餐中")
    public Result<?> updateOrderReady( @RequestBody @Valid UpdateOrderForm updateOrderForm) throws Exception{
        String msg = orderProductService.updateOrder(updateOrderForm.getOrderId(),OrderStatus.ORDER_PREPARATION);
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    //更新订单为配送中
    @PutMapping("/updateOrderDeliver")
    @ApiOperation(value = "更新订单为配送中")
    @RequireRole({"商家"})
    public Result<?> updateOrderDeliver( @RequestBody @Valid UpdateOrderForm updateOrderForm) throws Exception{
        String msg = orderProductService.updateOrder(updateOrderForm.getOrderId(),OrderStatus.ORDER_DELIVERY);
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    //更新订单为已送达
    @PutMapping("/updateOrderArrived")
    @ApiOperation(value = "更新订单为已送达")
    @RequireRole({"商家"})
    public Result<?> updateOrderArrived( @RequestBody @Valid UpdateOrderForm updateOrderForm) throws Exception{
        String msg = orderProductService.updateOrder(updateOrderForm.getOrderId(),OrderStatus.ORDER_DELIVERED);
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    //更新订单为已取消
    @PutMapping("/updateOrderCancel")
    @ApiOperation(value = "更新订单为已取消")
    @RequireRole({"商家"})
    public Result<?> updateOrderCancel(@RequestBody @Valid UpdateOrderForm updateOrderForm,@RequestHeader("token") String token) throws Exception{
        Claims claims = JwtUtil.parseToken(token);
        String userId = String.valueOf(claims.get("userId"));
        String roleId = String.valueOf(claims.get("roleId"));
        String msg = orderProductService.cancelOrder(updateOrderForm.getOrderId(),userId,roleId);
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    //更新订单为已退款
    @PutMapping("/updateOrderRefund")
    @ApiOperation(value = "更新订单为已退款")
    @RequireRole({"商家"})
    public Result<?> updateOrderRefund(@ApiParam("订单编号") @RequestBody @Valid UpdateOrderForm updateOrderForm) throws Exception{
        String msg = orderProductService.refundOrder(updateOrderForm.getOrderId());
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    //更新订单为结束订单
    @PutMapping("/updateOrderEnd")
    @ApiOperation(value = "更新订单为结束订单")
    @RequireRole({"商家"})
    public Result<?> updateOrderEnd(@ApiParam("订单编号") @RequestBody @Valid UpdateOrderForm updateOrderForm) throws Exception{
        String msg = orderProductService.closeOrder(updateOrderForm.getOrderId());
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
    @PutMapping("/queryOrderPay")
    @ApiOperation(value = "查询订单支付状态")
    @RequireRole({"商家"})
    public Result<?> queryOrderPay(@RequestBody @Valid CommonsOrderForm commonsOrderForm) throws Exception{
        String msg = orderProductService.alipayQuery(commonsOrderForm.getOrderId());
        return Result.getResult(String.class).setCode(200).setMsg(msg);
    }
}


